package handlers

import (
	"backEnd/database"
	"backEnd/models"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// GetClassify 获取壁纸大分类
func GetClassify(c *gin.Context) {
	startTime := time.Now()

	// 获取参数
	selectParam := c.Query("select")
	pageNum, _ := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "8"))

	var query string
	var args []interface{}

	if selectParam == "true" {
		// 推荐分类，不使用分页
		query = `
			SELECT id, name, sort, picurl, is_select, update_time 
			FROM wallpaper_classify 
			WHERE is_select = 1 
			ORDER BY sort ASC
		`
	} else {
		// 分页查询
		offset := (pageNum - 1) * pageSize
		query = `
			SELECT id, name, sort, picurl, is_select, update_time 
			FROM wallpaper_classify 
			ORDER BY sort ASC 
			LIMIT ? OFFSET ?
		`
		args = append(args, pageSize, offset)
	}

	rows, err := database.DB.Query(query, args...)
	if err != nil {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "查询失败",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}
	defer rows.Close()

	var classifies []models.WallpaperClassify
	for rows.Next() {
		var classify models.WallpaperClassify
		var isSelect int
		err := rows.Scan(&classify.ID, &classify.Name, &classify.Sort, &classify.PicURL, &isSelect, &classify.UpdateTime)
		if err != nil {
			continue
		}
		classify.Select = isSelect == 1
		classifies = append(classifies, classify)
	}

	// 获取总数
	var total int
	if selectParam != "true" {
		countQuery := "SELECT COUNT(*) FROM wallpaper_classify"
		database.DB.QueryRow(countQuery).Scan(&total)
	} else {
		total = len(classifies)
	}

	c.JSON(http.StatusOK, models.Response{
		ErrCode:  0,
		ErrMsg:   "查询成功",
		Data:     classifies,
		Total:    &total,
		TimeCost: time.Since(startTime).Milliseconds(),
	})
}
